package com.ebt.m.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.ebt.m.utils.fileutils.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Damon.Han on 2017/4/18 0018.
 *
 * @author Damon
 */

public class FileDownloader {
    private ProgressDialog
            progressDialog;
    // 创建okHttpClient对象
    private OkHttpClient mOkHttpClient = new OkHttpClient();
    private Handler mHandler = null;
    private Context context;
//    private Handler mHandler = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case 1:
//                    int progress = msg.arg1;
//                    if (progressDialog != null) {
//                        progressDialog.setMessage(progress + "");
//                    }
//                    break;
//
//                default:
//                    break;
//            }
//            super.handleMessage(msg);
//        }
//    };

    /**
     * @param mProgressBar
     */
    public FileDownloader(Activity activity, ProgressDialog mProgressBar) {
        this.progressDialog = mProgressBar;
        this.context = activity;
        if (progressDialog == null && activity != null) {
            progressDialog = new ProgressDialog(activity);
            progressDialog.setCancelable(false);
            progressDialog.setMessage("正在打开文件...");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }
    }

    public void downLoadPdf(final String url, String fileDiaplayName) {
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File f = new File(ConfigData.PATH_CACHE_PDFS);
                    if (!f.exists()) {
                        f.mkdirs();
                    }
                    String name = getNameFromUrl(url);
                    File file = new File(ConfigData.PATH_CACHE_PDFS, name);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        Log.d("h_bl", "progress=" + progress);
                        if (mHandler != null) {
                            Message msg = mHandler.obtainMessage();
                            msg.what = 1;
                            msg.arg1 = progress;
                            mHandler.sendMessage(msg);
                        }
                    }
                    fos.flush();
                    Log.d("h_bl", "文件下载成功");
                    //下载成功
                    if (file.exists()) {
                        FileUtils.openFile(context, file);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("h_bl", "文件下载失败");
                } finally {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

}
